package cn.gem.rainbow.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@Slf4j
public class UploadAndDownController {

    @Value("${system-param.appUploadDir}")
    private String appUploadDir;

    /**
     * MultipartFile 文件上传，不限文件格式
     *
     * <form method="post" action="/upload" enctype="multipart/form-data">
     *     <input type="file" name="file"><br>
     *     <input type="submit" value="提交">
     * </form>
     *
     * @param file MultipartFile
     * @return String
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String filePath = appUploadDir;
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败！";
    }

    /**
     * MultipartFile 多图上传
     *
     * <form method="post" action="/multiUpload" enctype="multipart/form-data">
     *     <input type="file" name="file"><br>
     *     <input type="file" name="file"><br>
     *     <input type="file" name="file"><br>
     *     <input type="submit" value="提交">
     * </form>
     *
     * @param request HttpServletRequest
     * @return  String
     */
    @PostMapping("/multiUpload")
    @ResponseBody
    public String multiUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filePath = appUploadDir;
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                return "上传第" + (i++) + "个文件失败";
            }
            String fileName = file.getOriginalFilename();

            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                log.info("第" + (i + 1) + "个文件上传成功");
            } catch (IOException e) {
                log.error(e.toString(), e);
                return "上传第" + (i++) + "个文件失败";
            }
        }

        return "上传成功";

    }
}
